package interfacegen.java

import java.util.ArrayList
import java.util.List
import org.eclipse.xtext.generator.IFileSystemAccess
import sdmakerz_v1.coresyntax.generator.interfaces.IContext
import sdmakerz_v1.coresyntax.generator.interfaces.IInterfaceData
import sdmakerz_v1.coresyntax.generator.interfaces.IMethodData
import sdmakerz_v1.coresyntax.generator.interfaces.ISDMakerFolderLevelGen
import sdmakerz_v1.coresyntax.SDMakerV1Utils

class JavaInterfaceGen implements ISDMakerFolderLevelGen {
	
	override doGenerate(IContext context, IFileSystemAccess fsa) {
	
		for(IInterfaceData interfaceData : context.interfacesDatas){
		
			fsa.generateFile("java-interface-generator-gen/"+
				interfaceData.getQualifiedName.replaceAll("\\.", "/")+".java",
				compileInterface(interfaceData));
		}
	}
	
	def CharSequence 
	compileInterface(IInterfaceData interfaceData){	
		var String qualifiedName= interfaceData.getQualifiedName;
		var List<String> clazzs= null;
		var int i= 0;
		var CharSequence charSequenceResult= 
		'''
		package «SDMakerV1Utils::computePackageName(qualifiedName)»;
		
		«FOR String importQualifiedName : computeNeededImports(interfaceData)»
		import «importQualifiedName»;
		«ENDFOR»
		
		public interface «SDMakerV1Utils::computeSimpleName(qualifiedName)»{
		'''
		
		 for(IMethodData methodData : interfaceData.allMethodData){
		 	clazzs= methodData.paramsRealType;
		 	charSequenceResult = charSequenceResult + '''public Object «methodData.methodName»('''
			
			i= 0;
			while(i < clazzs.size - 1){
				charSequenceResult = charSequenceResult + '''«SDMakerV1Utils::computeSimpleName(clazzs.get(i))» arg«i», '''
				i= i +1;
			}
			
			if(clazzs.size > 0){
				charSequenceResult = charSequenceResult + '''«SDMakerV1Utils::computeSimpleName(clazzs.get(i))» arg«i»'''
			}
			

			charSequenceResult = charSequenceResult + ''');
			'''
		}
		
		charSequenceResult = charSequenceResult + '''
		}'''
		
		return charSequenceResult;
	}
	
	def List<String> 
	computeNeededImports(IInterfaceData interfaceData){
		var List<String> computedImports= new ArrayList<String>();
		
		for(IMethodData methodData : interfaceData.allMethodData){
			for(String clazz : methodData.paramsRealType){
				
				if(SDMakerV1Utils::contains(computedImports, clazz)==false &&
					clazz.compareTo(interfaceData.qualifiedName)!=0 &&
					clazz.compareTo(typeof(Boolean).name)!=0 &&
					clazz.compareTo(typeof(Integer).name)!=0 &&
					clazz.compareTo(typeof(Double).name)!=0 &&
					clazz.compareTo(typeof(Character).name)!=0 &&
					clazz.compareTo(typeof(String).name)!=0){
						
						computedImports.add(clazz);
				}
			}
		}
		
		return computedImports;
	}	
}